"""
数据源字段模型
"""
from sqlalchemy import Column, Integer, String, Boolean, Text, ForeignKey, DateTime
from sqlalchemy.orm import relationship
from sqlalchemy.sql import func
from database import Base


class DataSourceField(Base):
    """数据源字段模型"""
    __tablename__ = "data_source_fields"

    id = Column(Integer, primary_key=True, index=True, comment="字段ID")
    data_source_id = Column(Integer, ForeignKey("data_sources.id"), nullable=False, comment="数据源ID")
    name = Column(String(100), nullable=False, comment="字段名称")
    display_name = Column(String(200), comment="显示名称")
    field_type = Column(String(50), nullable=False, comment="字段类型")
    description = Column(Text, comment="字段描述")
    is_primary = Column(Boolean, default=False, comment="是否主键")
    is_nullable = Column(Boolean, default=True, comment="是否可空")
    is_email = Column(Boolean, default=False, comment="是否邮箱字段")
    is_name = Column(Boolean, default=False, comment="是否姓名字段")
    sample_value = Column(Text, comment="样例值")
    data_format = Column(String(100), comment="数据格式")
    created_at = Column(DateTime(timezone=True), server_default=func.now(), comment="创建时间")
    updated_at = Column(DateTime(timezone=True), server_default=func.now(), onupdate=func.now(), comment="更新时间")

    # 关系
    data_source = relationship("DataSource", back_populates="fields")

    def __repr__(self):
        return f"<DataSourceField(name='{self.name}', type='{self.field_type}')>"


# 字段类型枚举
FIELD_TYPES = {
    "text": "文本",
    "number": "数字", 
    "email": "邮箱",
    "date": "日期",
    "datetime": "日期时间",
    "boolean": "布尔值",
    "json": "JSON",
    "longtext": "长文本",
    "url": "链接",
    "phone": "电话",
    "currency": "货币",
}
